// 用户认证服务

// 模拟用户数据存储
let users = JSON.parse(localStorage.getItem('users')) || [];
let currentUser = JSON.parse(localStorage.getItem('currentUser')) || null;

// 保存用户数据到本地存储
const saveUsers = () => {
  localStorage.setItem('users', JSON.stringify(users));
};

// 保存当前用户到本地存储
const saveCurrentUser = () => {
  localStorage.setItem('currentUser', JSON.stringify(currentUser));
};

// 注册新用户
export const register = (username, password) => {
  // 检查用户名是否已存在
  const existingUser = users.find(user => user.username === username);
  if (existingUser) {
    throw new Error('用户名已存在');
  }
  
  // 创建新用户，包含基本个人信息字段
  const newUser = {
    id: Date.now().toString(),
    username,
    password,
    nickname: username, // 默认昵称与用户名相同
    avatar: `https://picsum.photos/seed/${username}/200/200`, // 随机头像
    email: '',
    phone: '',
    address: '',
    gender: '',
    birthDate: '',
    createdAt: new Date().toISOString()
  };
  
  users.push(newUser);
  saveUsers();
  return newUser;
};

// 用户登录
export const login = (username, password) => {
  const user = users.find(user => user.username === username && user.password === password);
  if (!user) {
    throw new Error('用户名或密码错误');
  }
  
  currentUser = {
    id: user.id,
    username: user.username,
    nickname: user.nickname,
    avatar: user.avatar
  };
  saveCurrentUser();
  return currentUser;
};

// 用户登出
export const logout = () => {
  currentUser = null;
  saveCurrentUser();
};

// 获取当前登录用户
export const getCurrentUser = () => {
  return currentUser;
};

// 检查用户是否已登录
export const isLoggedIn = () => {
  return currentUser !== null;
};

// 获取用户完整信息
export const getUserInfo = (userId) => {
  return users.find(user => user.id === userId) || null;
};

// 更新用户信息
export const updateUserInfo = (userId, userInfo) => {
  const userIndex = users.findIndex(user => user.id === userId);
  if (userIndex === -1) {
    throw new Error('用户不存在');
  }
  
  // 更新用户信息，但不修改密码和创建时间
  const { password, createdAt, ...updatableInfo } = userInfo;
  users[userIndex] = {
    ...users[userIndex],
    ...updatableInfo,
    updatedAt: new Date().toISOString()
  };
  
  // 如果更新的是当前登录用户，也要更新currentUser
  if (currentUser && currentUser.id === userId) {
    currentUser = {
      ...currentUser,
      nickname: users[userIndex].nickname || currentUser.username,
      avatar: users[userIndex].avatar
    };
    saveCurrentUser();
  }
  
  saveUsers();
  return users[userIndex];
};

// 更改密码
export const changePassword = (userId, oldPassword, newPassword) => {
  const userIndex = users.findIndex(user => user.id === userId);
  if (userIndex === -1) {
    throw new Error('用户不存在');
  }
  
  const user = users[userIndex];
  if (user.password !== oldPassword) {
    throw new Error('原密码错误');
  }
  
  if (newPassword.length < 6) {
    throw new Error('新密码长度不能少于6位');
  }
  
  user.password = newPassword;
  user.passwordUpdatedAt = new Date().toISOString();
  
  saveUsers();
  return user;
};